<script setup>
import { reactive, ref, computed, watch } from "vue"
const form = reactive({
  title: "",
  date: "",
})
const arr = reactive(JSON.parse(localStorage.getItem("arr") || "[]"))
const selected = ref(-1) // -1 添加 0-n 修改
const currentIndex = ref(0)
const displayArr = computed(() => {
  return arr.slice(currentIndex.value, currentIndex.value + 10)
})
watch(
  () => arr,
  () => {
    localStorage.setItem("arr", JSON.stringify(arr))
  },
  { deep: true }
)
const onSubmit = () => {
  if (selected.value === -1) {
    // 添加
    // 因为 id 是唯一的，如果不这样配置，那么就会出现 id 重复的情况
    arr.push({ ...form, id: Date.now() + Math.floor(Math.random() * 1000) })
  } else {
    // 修改
    arr[selected.value] = { ...arr[selected.value], ...form }
  }
  // form.id = ""
  form.title = ""
  form.date = ""
  selected.value = -1
}


const onEdit = (index) => {
  selected.value = index
  form.title = arr[index].title
  form.date = arr[index].date
}
const onDelete = (index) => {
  arr.splice(index, 1)
}
const onClear = () => {
  arr.splice(0, arr.length)
}
const onMock = () => {
  for (let i = 1; i <= 10; i++) {
    arr.push({
      title: i + "",
      date: "2020-01-01",
      id: i + "",
    })
  }
}

const onDragStart = (e, index) => {
  e.dataTransfer.setData("index", index)
}
const onDragOver = (e) => {
  e.preventDefault()
}
const onDrop = (e, targetIndex) => {
  //
  e.preventDefault()
  const originIndex = parseInt(e.dataTransfer.getData("index"))
  // drop 时改变顺序
  const item = arr.splice(originIndex, 1)[0]
  arr.splice(targetIndex, 0, item)
};


</script>

<template>
  <div>

    <input type="text" v-model="form.title" />
    <input type="date" v-model="form.date" />
    <button @click="onSubmit">{{ selected === -1 ? '添加' : '提交' }}</button>
  </div>
  <div>
    <button @click="onMock">模拟数据</button>
    <button @click="onClear">清空数据</button>
  </div>
  <table>
    <thead>
      <tr>
        <th>标题</th>
        <th>日期</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item, index) in arr" :key="item.id" draggable="true" @dragstart="onDragStart($event, index)"
        @dragover="onDragOver" @drop="onDrop($event, index)">
        <td>{{ item.title }}</td>
        <td>{{ item.date }}</td>
        <td>
          <button @click="onEdit(index)">修改</button>
          <button @click="onDelete(index)">删除</button>
        </td>
      </tr>
    </tbody>
  </table>
</template>